//
/* 标准方法：加载、保存、调试项目，弹出任务面板、日历面板。
----------------------------------------------------------------------------- */
var ServicesPath = mini_JSPath + '././plusproject/services/' // Ajax交互路径（根据实际项目部署路径，需要修改）

var Url = ''
var proinfoId = ''

function doSetProjectData (project, dataProject) {
  if (project.showProjectTask) {
    var root = {
      Name: dataProject.Name,
      isProject: true
    }
    root.children = dataProject.Tasks

    dataProject.Tasks = [root]

    project.loadData(dataProject)

    // 如果是将项目作为顶级父任务，则需要处理下数据联动

    project.orderProject()
  } else {
    project.loadData(dataProject)
  }
}

function doGetProjectData (project) {
  var dataProject = project.getData()
  dataProject.RemovedTasks = project.getRemovedTasks()

  if (project.showProjectTask) {
    var Tasks = dataProject.Tasks

    var root = Tasks[0]
    if (root && root.isProject) { // 如果第一条任务是项目任务，则克隆一个新项目数据
      dataProject.Tasks = []
      var clone = mini.clone(dataProject)
      dataProject.Tasks = Tasks // 还原原始数据

      dataProject = clone
      dataProject.Tasks = root.children
    }
  }

  return dataProject
}

function LoadProject (params, proinfoid, gattloadUrl, elementUrl, project, callback) {
  if (typeof params !== 'object') {
    params = {
      projectuid: params,
      proInfoId: proinfoid
    }
  }
  Url = elementUrl
  proinfoId = proinfoid
  project.loading()

  // axios.request({
  //   url: 'User/LoginInfo',
  //   method: 'post',
  // });
  $.ajax({
    url: gattloadUrl,
    data: params,
    cache: false,
    success: function (text) {
      var dataProject = mini.decode(text)
      if (dataProject != 0) {
        doSetProjectData(project, dataProject)
        // SetPData(project, project.data.Tasks[0]);

        // project.orderProject();

        // 加载时自动排程，如果有变动，需要提示
        //            if (project.isChanged()) {
        //                alert("项目数据加载时自动调整");
        //            }

        //
        if (callback) callback(project)
      }
      project.unmask()
    },
    error: function (jqXHR, textStatus, errorThrown) {
      alert('加载失败, 错误码：' + textStatus)
      project.unmask()
    }
  })
}

function LoadProjectAPP (params, proinfoid, gattloadUrl, elementUrl, project, GanttId, callback) {
  if (typeof params !== 'object') {
    params = {
      projectuid: params,
      proInfoId: proinfoid
    }
  }
  Url = elementUrl
  proinfoId = proinfoid
  project.loading()

  // axios.request({
  //   url: 'User/LoginInfo',
  //   method: 'post',
  // });
  $.ajax({
    url: gattloadUrl,
    data: params,
    cache: false,
    success: function (text) {
      var dataProject = mini.decode(text)
      if (dataProject != 0) {
        doSetProjectData(project, dataProject)
        SetPData(project, project.data.Tasks[0], GanttId)

        // project.orderProject();

        // 加载时自动排程，如果有变动，需要提示
        //            if (project.isChanged()) {
        //                alert("项目数据加载时自动调整");
        //            }

        //
        if (callback) callback(project)
      }
      project.unmask()
    },
    error: function (jqXHR, textStatus, errorThrown) {
      alert('加载失败, 错误码：' + textStatus)
      project.unmask()
    }
  })
}

function LoadNewElementList (task, project) {
  var params = {
    UID: task.UID,
    proinfoId: proinfoId
  }
  var tasknew = task
  console.log('1123', task)
  console.log('324', project)
  $.ajax({
    url: Url,
    data: params,
    cache: false,
    success: function (text) {
      var dataProject = mini.decode(text)
      tasknew.ElementListNew = dataProject
      project.updateTask(task, tasknew)
      console.log('11235654', tasknew)
    },
    error: function (jqXHR, textStatus, errorThrown) {
      alert('加载失败, 错误码：' + textStatus)
      project.unmask()
    }
  })
}

function LoadProject2 (uid, OrderByValue, gattloadUrl, project, callback) {
  if (typeof params !== 'object') {
    params = {
      projectuid: uid,
      OrderByValue: OrderByValue
    }
  }

  project.loading()

  //      axios.request({
  //         url:'wp/Gantt/Load',
  //         method:'get',
  //         data:params
  //     }).then(text => {
  //         var dataProject = mini.decode(text);

  //             doSetProjectData(project, dataProject);

  //             //project.orderProject();

  //             //加载时自动排程，如果有变动，需要提示
  // //            if (project.isChanged()) {
  // //                alert("项目数据加载时自动调整");
  // //            }

  //             //
  //             if (callback) callback(project);
  //             project.unmask();
  //       });
  $.ajax({
    url: gattloadUrl,
    data: params,
    cache: false,
    success: function (text) {
      var dataProject = mini.decode(text)
      if (dataProject != 0) {
        doSetProjectData(project, dataProject)

        // project.orderProject();

        // 加载时自动排程，如果有变动，需要提示
        //            if (project.isChanged()) {
        //                alert("项目数据加载时自动调整");
        //            }

        //
        if (callback) callback(project)
      }

      project.unmask()
    },
    error: function (jqXHR, textStatus, errorThrown) {
      alert('加载失败, 错误码：' + textStatus)
      project.unmask()
    }
  })
}

function SvaeElementLik (project) {
  var modified = project.tasks.getChanges('modified', false)
  if (modified.length > 0) {
    modified.forEach(function (co) {
      var task = co
      if (co.ElementList.length > 0) {
        var start, finish, actualstart, actualfinish, planstart, planfinish
        var iii = 0
        co.ElementList.forEach(function (o) {
          if (iii == 0) {
            start = o.StartDate
            finish = o.EndDate
            actualstart = o.ActualStartDate
            actualfinish = o.ActualEndDate
            planstart = o.PlanStartDate
            planfinish = o.PlanEndDate
          } else {
            if (start > o.StartDate) {
              start = o.StartDate
            }
            if (finish < o.EndDate) {
              finish = o.EndDate
            }
            if (actualstart > o.ActualStartDate) {
              actualstart = o.ActualStartDate
            }
            if (actualfinish < o.ActualEndDate) {
              actualfinish = o.ActualEndDate
            }
            if (planstart > o.PlanStartDate) {
              planstart = o.PlanStartDate
            }
            if (planfinish < o.PlanEndDate) {
              planfinish = o.PlanEndDate
            }
          }
          iii += 1
        })
        var start_ = 0
        var finish_ = 0
        var actualstart_ = 0
        var actualfinish_ = 0
        var planstart_ = 0
        var planfinish_ = 0
        if (start && co.Start) {
          start_ = co.Start.getTime() - start.getTime()
        }
        if (finish && co.Finish) {
          finish_ = co.Finish.getTime() - finish.getTime()
        }
        if (actualstart && co.ActualStart) {
          actualstart_ = co.ActualStart.getTime() - actualstart.getTime()
        }
        if (actualfinish && co.ActualFinish) {
          actualfinish_ = co.ActualFinish.getTime() - actualfinish.getTime()
        }
        if (planstart && co.PlanStart) {
          planstart_ = co.PlanStart.getTime() - planstart.getTime()
        }
        if (planfinish && co.PlanFinish) {
          planfinish_ = co.PlanFinish.getTime() - planfinish.getTime()
        }
        co.ElementList.forEach(function (o) {
          if (o.EndDate) {
            o.StartDate = new Date(o.StartDate.getTime() + start_)
          }
          if (o.EndDate) {
            o.EndDate = new Date(o.EndDate.getTime() + finish_)
          }
          if (o.ActualStartDate) {
            o.ActualStartDate = new Date(o.ActualStartDate.getTime() + actualstart_)
          }
          if (o.PlanStartDate) {
            o.PlanStartDate = new Date(o.PlanStartDate.getTime() + actualfinish_)
          }
          if (o.PlanStartDate) {
            o.PlanStartDate = new Date(o.PlanStartDate.getTime() + planstart_)
          }
          if (o.PlanEndDate) {
            o.PlanEndDate = new Date(o.PlanEndDate.getTime() + planfinish_)
          }
        })
        project.updateTask(task, co)
      }
    })
  }
}

function SaveProject (project, gattsaveUrl, callback, params) {
  SvaeElementLik(project)
  var dataProject = doGetProjectData(project)
  // var ChildTasks = project.getChildTasks(dataProject);
  // SetPData(dataProject.Tasks);

  var json = mini.encode(dataProject)
  project.mask('数据保存中，请稍后...')

  if (!params) {
    params = {
      project: json
    }
  }
  params.project = json
  $.ajax({
    url: gattsaveUrl,
    type: 'post',
    data: params,
    success: function (text) {
      // alert("保存成功,项目UID：" + text);
      alert('保存成功')
      project.acceptChanges()
      if (callback) callback(project)
      project.unmask()
    },
    error: function (jqXHR, textStatus, errorThrown) {
      alert('保存失败, 错误码：' + textStatus)
      project.unmask()
    }
  })
}

function SetPData (project, task, GanttId) {
  var ChildTasks = project.getChildTasks(task)
  if (ChildTasks.length > 0) {
    ChildTasks.forEach(function (o) {
      SetPData(project, o, GanttId)
    })
  } else {
    if (task.UID == GanttId) {
      if (task.ActualStart || task.ActualStart != '') {
        project.updateTask(task, 'PredecessorLink', [])
        project.updateTask(task, 'Start', task.ActualStart)
        var pantask = project.getAncestorTasks(task) // 所有上级节点
        pantask = pantask.reverse()
        pantask.forEach(function (o) {
          var ch = project.getChildTasks(o)
          var i = 0
          var StartData = task.ActualStart
          ch.forEach(function (co) {
            if (co.ActualStart != null) {
              i++
              if (co.ActualStart < StartData) {
                StartData = co.ActualStart
              }
            }
          })
          if (StartData && StartData != '') {
            project.updateTask(o, 'ActualStart', StartData)
            project.updateTask(o, 'Start', StartData)
          }
        })
      }
      if (task.ActualFinish || task.ActualFinish != '') {
        var duration = parseInt(Math.abs(task.ActualFinish - task.ActualStart) / 1000 / 60 / 60 / 24) + 1
        project.updateTask(task, 'Duration', duration)
        // project.updateTask(task, "Finish", task.ActualFinish);
        var pantask = project.getAncestorTasks(task)
        pantask = pantask.reverse()
        pantask.forEach(function (o) {
          var ch = project.getChildTasks(o)
          var i = 0
          var FinishData = task.ActualFinish
          ch.forEach(function (co) {
            if (co.ActualFinish != null) {
              i++
              if (co.ActualFinish > FinishData) {
                FinishData = co.ActualFinish
              }
            }
          })
          if (i == ch.length) {
            project.updateTask(o, 'ActualFinish', FinishData)
            project.updateTask(o, 'Finish', FinishData)
          }
        })
      }
    }
  }
  var modified = project.tasks.getChanges('modified', false)
  if (modified.length > 0) {
    modified.forEach(function (co) {
      var task = co
      if (task.ActualStart && task.ActualStart != '') {
        project.updateTask(task, 'ActualStart', task.Start)
      }
      if (task.ActualFinish && task.ActualFinish != '') {
        project.updateTask(task, 'ActualFinish', task.Finish)
      }
    })
  }
}

function AllSaveProject (project, gattsaveUrl, callback, params) {
  SvaeElementLik(project)
  var dataProject = doGetProjectData(project)

  var json = mini.encode(dataProject)

  // project.mask("数据保存中，请稍后...");

  if (!params) {
    params = {
      project: json
    }
  }
  // params.project =json;
  $.ajax({
    url: gattsaveUrl,
    type: 'post',
    data: params,
    success: function (text) {
      // alert("保存成功,项目UID：" + text);
      // alert("保存成功");
      project.acceptChanges()
      if (callback) callback(project)
      project.unmask()
    },
    error: function (jqXHR, textStatus, errorThrown) {
      alert('保存失败, 错误码：' + textStatus)
      project.unmask()
    }
  })
}

function TrackProject (project) {
  //    var list = project.getTaskList();
  //    list.forEach(function (o) {
  //        delete o._id;
  //        delete o._uid;
  //        delete o._pid;
  //        delete o._level;
  //        delete o._x;
  //        delete o._state;
  //    });

  var dataProject = project.getData()
  var json = mini.encode(dataProject)
  document.write(json)
  // 把生成的项目JSON数据发送给技术支持人员，方便技术人员进行调试定位项目问题
}

function LoadJSONProject (url, project, callback) {
  project.loading()
  $.ajax({
    url: url,
    cache: false,
    success: function (text) {
      var dataProject = mini.decode(text)

      doSetProjectData(project, dataProject)

      if (callback) callback(project)
      project.unmask()
    },
    error: function (jqXHR, textStatus, errorThrown) {
      alert('加载失败, 错误码：' + textStatus)
      project.unmask()
    }
  })
}

// 创建任务面板
var obj = {}
var bimEngine
var taskWindow = null

function ShowTaskWindow (project, tabName) {
  var task = project.getSelected()
  obj.bimEngine = project.bimEngine
  if (task) {
    if (!taskWindow) {
      taskWindow = new TaskWindow()
    }
    taskWindow.setTitle('编辑任务')
    // 加载新关联构件
    LoadNewElementList(task, project)
    taskWindow.show()

    taskWindow.setData(task, project,
      function (action) {
        if (action == 'ok') {
          try {
            var taskData = taskWindow.getData()
            taskData.ElState = 'true'
            console.log('taskData', taskData)
            project.updateTask(task, taskData)
            if (taskData.ActualStart) {
              // if (task.PredecessorLink.length > 0) {
              //   var predecessorUID = task.PredecessorLink[0].PredecessorUID;
              //   var link = project.getTask(predecessorUID);
              //   if (task.PredecessorLink[0].Type == 3) {
              //     var lin = parseInt((taskData.ActualStart - link.Start) / (1000 * 60 * 60 * 24))
              //     if (taskData.ActualStart < link.Start) {
              //       lin = lin;
              //     } else if (taskData.ActualStart > link.Start) {
              //       lin = lin;
              //     } else {
              //       lin = lin;
              //     }
              //     task.PredecessorLink[0].LinkLag = lin;

              //   } else {
              //     var lin = parseInt((taskData.ActualStart - link.Finish) / (1000 * 60 * 60 * 24))
              //     if (taskData.ActualStart < link.Finish) {
              //       lin = lin - 1;
              //     } else if (taskData.ActualStart > link.Finish) {
              //       lin = lin;
              //     } else {
              //       lin = lin - 1;
              //     }
              //     task.PredecessorLink[0].LinkLag = lin;
              //     task.PredecessorLink[0].Type = "1"
              //   }
              //   project.updateTask(task, "PredecessorLink", task.PredecessorLink);
              // }
              project.updateTask(task, 'PredecessorLink', [])
              project.updateTask(task, 'Start', taskData.ActualStart)
              var pantask = project.getAncestorTasks(task) // 所有上级节点
              pantask = pantask.reverse()
              pantask.forEach(function (o) {
                var ch = project.getChildTasks(o)
                var i = 0
                var StartData = taskData.ActualStart
                ch.forEach(function (co) {
                  if (co.ActualStart != null) {
                    i++
                    if (co.ActualStart < StartData) {
                      StartData = co.ActualStart
                    }
                  }
                })

                project.updateTask(o, 'ActualStart', StartData)
                project.updateTask(o, 'Start', StartData)
              })
            } else {
              var pantask = project.getAncestorTasks(task)
              pantask = pantask.reverse()
              pantask.forEach(function (o) {
                var ch = project.getChildTasks(o)
                var i = 0
                ch.forEach(function (co) {
                  if (co.ActualStart == null) {
                    i++
                  }
                })
                if (i == ch.length) {
                  project.updateTask(o, 'ActualStart', null)
                }
              })
            }
            if (taskData.ActualFinish) {
              project.updateTask(task, 'Finish', taskData.ActualFinish)
              var pantask = project.getAncestorTasks(task)
              pantask = pantask.reverse()
              pantask.forEach(function (o) {
                var ch = project.getChildTasks(o)
                var i = 0
                var FinishData = taskData.ActualFinish
                ch.forEach(function (co) {
                  if (co.ActualFinish != null) {
                    i++
                    if (co.ActualFinish > FinishData) {
                      FinishData = co.ActualFinish
                    }
                  }
                })
                if (i == ch.length) {
                  project.updateTask(o, 'ActualFinish', FinishData)
                  project.updateTask(o, 'Finish', FinishData)
                }
              })
            } else {
              var pantask = project.getAncestorTasks(task)
              pantask = pantask.reverse()
              var i = 0
              pantask.forEach(function (o) {
                var ch = project.getChildTasks(o)

                ch.forEach(function (co) {
                  if (co.ActualFinish == null) {
                    i++
                  }
                })
                if (i > 0) {
                  project.updateTask(o, 'ActualFinish', null)
                }
              })
            }
          } catch (ex) {
            alert('error:' + ex.message)
            return false
          }
        }
      }
    )
    if (tabName) {
      taskWindow.activeTab(tabName)
    }
  } else {
    alert('请先选择任务')
  }
}

// 日历面板

var calendarWindow = null

function ShowCalendarWindow (project) {
  if (!calendarWindow) {
    calendarWindow = new CalendarWindow()
  }
  calendarWindow.show()
  calendarWindow.setData(project.getCalendars(), project,
    function (action) {
      if (action == 'ok') {
        var calendars = calendarWindow.getData()
        var calendarUID = calendarWindow.CalendarsCombo.getValue()

        project.beginUpdate()
        project.setCalendars(calendars)
        project.setCalendarUID(calendarUID)
        project.endUpdate()
      }
    }
  )
}

// 资源面板
var resourcesWindow

function ShowResourcesWindow (project) {
  if (!resourcesWindow) {
    resourcesWindow = new ResourcesWindow()
  }
  resourcesWindow.show()
  resourcesWindow.setData(project.data.Resources, project,
    function (action) {
      if (action == 'ok') {
        var resources = resourcesWindow.getData()
        project.setResources(resources)
      }
    }
  )
}
